//
//  HLSearchViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/1.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLSearchViewController.h"
#import "HLSearchCell.h"
#import "HLUserInfo.h"
#import "HttpRequestManager.h"
#import "MBProgressHUD+HL.h"
#import "HLMoreCourse.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "HLCourseFoldViewController.h"
#import "HLFoldCourse.h"
#import "HLArticleViewController.h"
#import "HLCourseDetailViewController.h"

#define kPageLimit 10

@interface HLSearchViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSString *_search_content;
    NSUInteger _curren_page;
}
/** tableView  */
@property (nonatomic ,strong) UITableView *tableView;
/** UITextField  */
@property (nonatomic ,strong) UITextField *input;
/** 数据源  */
@property (nonatomic ,strong) NSMutableArray *dataSource;


@end

@implementation HLSearchViewController

#pragma mark - Lazy

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_input resignFirstResponder];
}

- (void)setupUI
{
    UIView *navTitleView = [[UIView alloc] init];
    navTitleView.frame = CGRectMake(0, 0, ScreenWidth - 120, 30);
    navTitleView.layer.cornerRadius = 15;
    navTitleView.clipsToBounds = YES;
    navTitleView.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = navTitleView;

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(7.5, 7.5, 15, 15)];
    imageView.image = [UIImage imageNamed:@"搜索按钮"];
    [navTitleView addSubview:imageView];
    
    UITextField *input = [[UITextField alloc] init];
    input.delegate = self;
    input.font = [UIFont systemFontOfSize:16];
    input.returnKeyType = UIReturnKeySearch;
    input.textColor = HLRGB(80, 80, 80);
    input.frame = CGRectMake(30, 1, navTitleView.frame.size.width - 30, 30);
    input.backgroundColor = [UIColor whiteColor];
    input.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入关键字" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16]}];
    input.tintColor = kColorMineBlueBG;
    _input = input;
    [navTitleView addSubview:input];

    [input becomeFirstResponder];
    
    [self configTableView];
}

- (void)configTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:0];;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    _tableView.backgroundColor = HLRGB(245, 245, 245);
    _tableView.rowHeight = 60;
    [_tableView registerClass:[HLSearchCell class] forCellReuseIdentifier:@"HLSearchCell"];
    [self.view addSubview:self.tableView];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadSearchRequest)];
    self.tableView.mj_footer.hidden = YES;
}

- (void)loadSearchRequest
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestSaerch signStr];
    params[@"userid"] = [HLUserInfo account].userid;
    params[@"search_content"] = _search_content;
    params[@"page"] = @(_curren_page);
    params[@"limit"] = @(kPageLimit);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestSaerch parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            NSArray *tempArray = [HLMoreCourse mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.dataSource addObjectsFromArray:tempArray];
            [weakSelf.tableView reloadData];
            
            _curren_page++;
            if (tempArray.count < kPageLimit) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }else{
            [weakSelf.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [weakSelf.tableView.mj_footer endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    if (textField.text.length == 0) {
        [MBProgressHUD showErrorMessage:@"请重新输入"];
    }else{
        /**** 重新搜索 删除数据 ****/
        [self.dataSource removeAllObjects];
        _curren_page = 1;
        _search_content = textField.text;
        self.tableView.mj_footer.hidden = NO;
        [self.tableView.mj_footer beginRefreshing];
    }
    return YES;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HLSearchCell"];
    HLMoreCourse *moreCourse = self.dataSource[indexPath.row];
    cell.textLabel.text = moreCourse.name;
    return cell;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
     [_input resignFirstResponder];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLMoreCourse *moreCourse = self.dataSource[indexPath.row];
    if([moreCourse.type integerValue] == 0){
        HLCourseFoldViewController *fold = [HLCourseFoldViewController new];
        fold.course = moreCourse;
        [self.navigationController pushViewController:fold animated:YES];
        return;
    }
    
    HLFoldCourse *foldCourse = [HLFoldCourse new];
    if ([moreCourse.type integerValue] == 2 ) {
        foldCourse.wkid =  moreCourse.ID;
        HLArticleViewController *article = [HLArticleViewController new];
        article.history_record_pic_url = moreCourse.pic;
        article.foldCourse = foldCourse;
        [self.navigationController pushViewController:article animated:YES];
        return;
    }
    
    if ([moreCourse.type integerValue] == 1) {
        foldCourse.wkid = moreCourse.ID;
        HLCourseDetailViewController *couseDetail = [HLCourseDetailViewController new];
        couseDetail.history_record_pic_url = moreCourse.pic;
        couseDetail.foldCourse = foldCourse;
        [self.navigationController pushViewController:couseDetail animated:YES];
    }
}




@end
